package top.wshape1.rpc.message.serializer;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2024-02-02
 */

public class JsonSerializer implements Serializer {

//    private static final Filter autoTypeFilter = JSONReader.autoTypeFilter(
//            ""
//    );

    @Override
    public <T> byte[] serialize(T object) {
        try {
            return JSON.toJSONBytes(object,
                    JSONWriter.Feature.FieldBased,
                    JSONWriter.Feature.ReferenceDetection,
                    JSONWriter.Feature.WriteClassName,
                    JSONWriter.Feature.NotWriteRootClassName,
                    JSONWriter.Feature.NotWriteDefaultValue,
                    JSONWriter.Feature.WriteEnumsUsingName
            );
        } catch (Exception e) {
            throw new RuntimeException("Serialization failed: " + e);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        try {
            // TODO SupportAutoType是不安全的
            return JSON.parseObject(bytes, clazz,
                    JSONReader.Feature.SupportClassForName,
                    JSONReader.Feature.FieldBased,
                    JSONReader.Feature.UseDefaultConstructorAsPossible,
                    JSONReader.Feature.IgnoreSetNullValue,
                    JSONReader.Feature.SupportAutoType);
        } catch (Exception e) {
            throw new RuntimeException("Deserialization failed: " + e);
        }
    }
}
